<template>
	<div class="dialog-container">
		<!-- 添加门店 -->
		<el-dialog :title="form.id ? '编辑供应商' : '添加供应商'" :append-to-body="true" :visible.sync="centerDialogVisible1" width="1000px" center
			@close="handleClose()">
			<div style="display: flex;position: relative;">
				<div>
					<el-form ref="form" style="width: 400px;height: 500px;overflow-y: auto;" :rules="rules" :model="form" label-width="100px">
						<el-form-item prop="xiaoqu_ids" label="关联小区">
							<el-select multiple filterable @change="selectXiaoqu" v-model="form.xiaoqu_ids" placeholder="请选择" style="width: 90%;" clearable>
								<el-checkbox
								style="margin-left: 10px;"
								v-model="check"
								:indeterminate="form.xiaoqu_ids.length !== xiaoqu.length"
								@change="selectAll">
								全选
								</el-checkbox>
								<el-option :label="item.xq_name" :value="item.id+''" v-for="(item, index) in xiaoqu" :key="item.id"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item prop="shop_name" label="门店名称">
							<el-input style="width: 90%" placeholder="请输入" clearable v-model="form.shop_name" />
						</el-form-item>
						<el-form-item prop="shop_log" label="门店logo">
							<div v-if="!form.shop_log" class="up-img" @click="upImg(1)"><i class="el-icon-plus" /></div>
							<img v-else class="up-img" width="100%" :src="form.shop_log + '?imageView2/1/w/150/h/150'"
								alt="" @click="upImg(1)">
						</el-form-item>
						<el-form-item prop="shop_address" label="门店地址">
							<el-input style="width: 90%" placeholder="请输入" clearable v-model="form.shop_address" />
						</el-form-item>
						<el-form-item prop="lngLat" label="门店经纬度">
							<div class="">
								<el-input style="width: 90%" placeholder="请输入" clearable v-model="form.lngLat" />
								<div style="color: red">* 格式为:121.336050,31.150960</div>
								<div style="color: #2196f3; padding-left: 10px">点击右侧地图获取坐标</div>
							</div>
						</el-form-item>
						<el-form-item prop="name" label="老板姓名">
							<el-input style="width: 90%" placeholder="请输入" clearable v-model="form.name" />
						</el-form-item>
						<el-form-item prop="phone" label="联系电话">
							<el-input style="width: 90%" maxLength="11" placeholder="请输入" clearable v-model="form.phone" />
						</el-form-item>
						<el-form-item prop="category_name" label="品类名称">
							<el-input style="width: 90%" placeholder="请输入" clearable v-model="form.category_name" />
						</el-form-item>
						<el-form-item prop="qualification" label="门店资质">
							<div v-if="!form.qualification" class="up-img" @click="upImg(2)"><i class="el-icon-plus" /></div>
							<img v-else class="up-img" width="100%" :src="form.qualification + '?imageView2/1/w/150/h/150'"
								alt="" @click="upImg(2)">
						</el-form-item>
						<el-form-item prop="state" label="门店状态">
							<el-switch v-model="form.state" :active-value="1" :inactive-value="2"></el-switch>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<div class="flex-center">
							<el-button @click="handleClose()">取 消</el-button>
							<el-button type="primary" @click="submit('form')">保 存</el-button>
						</div>
					</div>
				</div>
				<div id="container" style="width:500px;height:540px;"></div>
				<div
					style="position: absolute;top: 10px;right: 60px;background: #fff;border-radius: 6px;padding: 10px;">
					<div id="myPageTop">
						<table>
							<tr>
								<td>
									<label @click="search">请输入关键字：</label>
								</td>
							</tr>
							<tr>
								<td>
									<input
										style="padding:8px 10px;border-radius: 6px;border:1px solid #eee;margin-top: 5px;"
										id="tipinput" />
								</td>
							</tr>
						</table>
					</div>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import Api from '@/api/pages/gys/index';
	import { checkNumber,validPhone,isZjOrSj } from '@/utils/validate.js';
	var autoOptions;
	var auto;
	var placeSearch;
	var map;

	export default {
		name: 'gysDetail',
		props: {
			datas: {
				type: Object,
				default: {},
			}
		},
		data() {
			return {
				centerDialogVisible1: true,
				form: {
					id: '',
					shop_name: '',
					shop_log: '', //门店logo
					shop_address: '', //门店地址
					lngLat: '', //经纬度
					latitude: '', //纬度
					longitude: '', //经度
					name: '',
					phone: '',
					category_name:'',
					qualification: '', //门店资质图片
					state: 1, //门店状态 1.正常 2.关闭
					xiaoqu_ids: [], //关联小区
				},
				xiaoqu:[],
				check:false,
				rules: {
					xiaoqu_ids: [{ type: 'array', required: true, message: '请选择小区', trigger: 'change' }],
					shop_name: [{ required: true, message: '请输入门店名称', trigger: 'change' }],
					shop_address: [{ required: true, message: '请输入门店地址', trigger: 'change' }],
					lngLat: [{ required: true, message: '请输入门店经纬度', trigger: 'change' }],
					shop_log: [{ required: true, message: '请上传门店logo', trigger: 'change' }],
					qualification: [{ required: true, message: '请上传门店资质', trigger: 'change' }],
					state: [{ required: true, message: '请选择门店状态', trigger: 'change' }],
					name: [{ required: true, message: '请输入老板姓名', trigger: 'change' }],
					category_name: [{ required: true, message: '请输入品类名称', trigger: 'change' }],
					phone: [{ required: true, message: '请输入联系电话', trigger: 'change' }],
				}
			}
		},
		beforeDestroy () {
			// 组件销毁前可销毁地图实例
			map && map.destroy()
			let ele = document.querySelectorAll('.amap-sug-result');
			ele.forEach(item=>{
				item.remove()
			})
		},
		mounted() {
			if(this.datas.id){
				let item = JSON.parse(JSON.stringify(this.datas));
				item.xiaoqu_ids = item.xiaoqu_ids?item.xiaoqu_ids.split(','):[];
				item.lngLat = item.longitude +','+ item.latitude;
				this.form = Object.assign(this.form,item);
			}
			// console.log(this.form)
			this.$nextTick(() => {
				this.initMap();
			})
			this.loadAllXiaoQu();
		},
		methods: {
			selectAll (checked) {
				if (checked) {
					this.form.xiaoqu_ids = this.xiaoqu.map(d => d.id+'');
					this.check=true;
				} else {
					this.form.xiaoqu_ids = [];
					this.check=false;
				}
			},
			
			selectXiaoqu(){
				if(this.form.xiaoqu_ids.length == this.xiaoqu.length){
					this.check=true;
				}else{
					this.check=false;
				}
			},
			
			//获取小区
			loadAllXiaoQu(){
				Api.loadAllXiaoQu().then(res => {
					if (res.state) {
						this.xiaoqu = res.data;
						this.selectXiaoqu();
					}
				})
			},
			
			// 搜索
			search() {
				console.log('搜索')
				// auto = new AMap.AutoComplete(autoOptions);
				// placeSearch = new AMap.PlaceSearch({
				//     map: map
				// });  
				this.initMap();
			},
			
			// 地图初始化
			initMap() {
				let lng = String(this.form.longitude) || '121.429876';
				let lat = String(this.form.latitude) || '31.153222';
				// console.log('String(this.lng)-----' + lng, 'this.lat===' + lat)

				map = new AMap.Map("container", {
					center: [lng,lat],
					zoom: 13,
					resizeEnable: true
				});
				let that = this;

				if (lat) {
					that.marker = new AMap.Marker({
						position: new AMap.LngLat(lng,lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
					});
					// 将创建的点标记添加到已有的地图实例：
					map.add(that.marker);
					that.$forceUpdate();
				}

				//为地图注册click事件获取鼠标点击出的经纬度坐标
				var clickEventListener = map.on('click', function(e) {
					// console.log(e.lnglat.getLng())
					// console.log(e.lnglat.getLat())
					that.form.longitude = e.lnglat.getLng();
					that.form.latitude = e.lnglat.getLat();
					that.form.lngLat = that.form.longitude + ',' + that.form.latitude;
					// console.log(that.form.lngLat)
					that.$forceUpdate();
					if (that.marker) {
						// 移除已创建的 marker
						map.remove(that.marker);
					}
					that.marker = new AMap.Marker({
						position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
					});
					// 将创建的点标记添加到已有的地图实例：
					map.add(that.marker);
				});
				autoOptions = {
					input: "tipinput"
				};
				AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete'], function() {
					// console.log('------')
					auto = new AMap.AutoComplete(autoOptions);
					placeSearch = new AMap.PlaceSearch({
						map: map
					});
					//构造地点查询类
					auto.on("select", select); //注册监听，当选中某条记录时会触发
					function select(e) {
						placeSearch.setCity(e.poi.adcode);
						placeSearch.search(e.poi.name); //关键字查询查询
						if (e.poi.location) {
							that.form.longitude = e.poi.location.lng;
							that.form.latitude = e.poi.location.lat;
							that.form.lngLat = e.poi.location.lng+ ',' + e.poi.location.lat;
							// console.log(that.form.lngLat)
							if (that.marker) {
								// 移除已创建的 marker
								map.remove(that.marker);
							}
							that.marker = new AMap.Marker({
								position: new AMap.LngLat(e.poi.location.lng, e.poi.location
								.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
							});
							// 将创建的点标记添加到已有的地图实例：
							map.add(that.marker);
							that.$forceUpdate();
						}
					}
				});
			},

			// 上传图片
			upImg(type) {
				// 上传单个文件
				this.hhFolder({
					max: 1,
					filter: 'image',
					thumb_w: 500,
					thumb_h: 250,
					success: files => {
						if (type == 1) {
							this.form.shop_log = files[0].url;
						} else {
							this.form.qualification = files[0].url;
						}
					}
				});
			},

			//关闭
			handleClose(done) {
				this.centerDialogVisible1 = false;
				this.$parent.colSupplier(done);
			},

			//保存
			async submit(formName) {
				this.$refs[formName].validate(async(valid) => {
					if (valid) {
						if (this.form.lngLat.indexOf(",") == -1) {
						    this.$message.error("门店经纬度格式不正确");
						    return;
						}
						if (!this.form.lngLat.split(",")[0] || !this.form.lngLat.split(",")[1]) {
						    this.$message.error("门店经纬度格式不正确");
						    return;
						}
						if (
						    !checkNumber(this.form.lngLat.split(",")[0]) ||
						    !checkNumber(this.form.lngLat.split(",")[1])
						) {
						    this.$message.error("门店经纬度格式不正确");
						    return;
						}
						if(!validPhone(this.form.phone)){
							this.$message.error("联系电话格式不正确");
							return;
						}

						let datas={
							'supplier.id': this.form.id,
							'supplier.shop_log': this.form.shop_log,
							'supplier.shop_name': this.form.shop_name,
							'supplier.shop_address': this.form.shop_address,
							'supplier.longitude': this.form.lngLat.split(",")[0],
							'supplier.latitude': this.form.lngLat.split(",")[1],
							'supplier.qualification': this.form.qualification,
							'supplier.name': this.form.name,
							'supplier.category_name': this.form.category_name,
							'supplier.phone': this.form.phone,
							'supplier.state': this.form.state,
							'supplier.xiaoqu_ids': this.form.xiaoqu_ids.join(','),
						}
						// console.log(datas)

						Api.supplierSaveUpd(datas).then((res) => {
							if (res.state) {
								this.$message({
									message: res.msg,
									type: "success"
								});
								this.handleClose(true);
							} else {
								this.$message.error(res.msg);
							}
						});
					}
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	.up-img {
		background-color: #fbfdff;
		border: 1px dashed #c0ccda;
		border-radius: 6px;
		-webkit-box-sizing: border-box;
		box-sizing: border-box;
		width: 100px;
		height: 100px;
		cursor: pointer;
		line-height: 100px;
		vertical-align: top;
		display: flex;
		justify-content: center;
		align-items: center;

		.el-icon-plus {
			font-size: 28px;
			color: #8c939d;
		}
	}

	.up-img:hover {
		border: 1px dashed #409eff;
	}
</style>

<style lang="scss">
	.amap-sug-result{
		z-index: 9999;
	}
	.shop-Deatil-dialog {
		.el-dialog {
			margin-bottom: 40px;
		}

		.el-dialog__body {
			padding: 15px 20px;
		}

		.el-form-item__label {
			font-size: 15px;
		}

	}
</style>
